'''
Created on Oct 18, 2012

@author: Cihat Basol
'''

import sys
import traceback

from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt


from dexen.system import client
from dexen.system.common import service

svr_proxy = client.GetServerProxy()


class ConnectDlg(QDialog):
    def __init__(self, parent):
        super(ConnectDlg, self).__init__(parent)
        self.setWindowTitle("Connect to Server")
        self._create_widgets()
        self.setFixedSize(self.sizeHint())
    
    def _create_widgets(self):
        self.label = QLabel("Server Address:")
        self.lineEdit = QLineEdit(service.get_my_ip())
        self.connectBtn = QPushButton("Connect")
        
        layout = QHBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.lineEdit)
        layout.addWidget(self.connectBtn) 
        
        self.setLayout(layout)

        # Configure signal/slots
        self.connect(self.connectBtn, SIGNAL("clicked()"), 
                     self.on_connectBtn_clicked)
    
    def on_connectBtn_clicked(self):
        try:
            self.setCursor(QCursor(Qt.WaitCursor))
            svr_addr = str(self.lineEdit.text())
            svr_proxy.connect(svr_addr)
            start_time = svr_proxy.get_start_time()
        except:
            traceback.print_tb(sys.exc_info()[2])
            print "Connection is failed"
            msgBox = QMessageBox(self)
            msgBox.setWindowTitle("Connection failure")
            msg = "Cannot access the dexen server.\n"
            msg += "Make sure the address is valid and the server is running." 
            msgBox.setText(msg)
            msgBox.exec_()
        else:
            self.emit(SIGNAL("connected"), svr_addr, start_time)
            self.accept()
        finally:
            self.setCursor(QCursor(Qt.ArrowCursor))    

